var jweixin = require('jweixin-module');
const defaultDesc = '！';
export default function setConfig(imgUrl) {
	if (!isWeixinBrowser()) {
		return;
	}
	loadShareSignature();
	jweixin.ready(function() {
		console.log("set success set")

		jweixin.updateAppMessageShareData({
			title: "新鲜有迹可 “寻”", // 分享标题
			desc: "72小时锁鲜 从源头直达您的厨房", // 分享描述
			link: window.location.href, // 分享链接
			imgUrl: imgUrl, // 分享图标
			success: function() {},
			trigger: function(res) {},
		});
		// 朋友
		jweixin.updateTimelineShareData({
			title: "新鲜有迹可 “寻”", // 分享标题
			desc: "72小时锁鲜 从源头直达您的厨房", // 分享描述
			link: window.location.href, // 分享链接
			imgUrl: imgUrl, // 分享图标
			success: function() {

			}
		});
	});
	jweixin.error(p => {
		console.log(p)
	});
}

function loadShareSignature() {
	if (sessionStorage.signature) {
		let signature = JSON.parse(sessionStorage.signature);
		setShareConfig(signature);
		return;
	}
	let userAgent = navigator.userAgent
	let url = ''

	if (userAgent.includes('iPhone') || userAgent.includes('iPad')) {
		url = sessionStorage.getItem('originUrl')
	} else {
		url = location.href
	}

	console.log("url:" + url);
	uni.request({
		url: "/wx/char/getShareSignature",
		method: 'GET',
		header: {
			'share-url': url
		},
		success: res => {
			console.log("getMachineNum success:" + JSON.stringify(res.data.data));
			if (res.data.errno != 0) {
				return
			}
			sessionStorage.signature = JSON.stringify(res.data.data);
			setShareConfig(res.data.data);

		},
		fail: (e) => {
			console.log("getMachineNum fail:" + JSON.stringify(e));
		},
		complete: () => {}
	});

}

function setShareConfig(shareSignature) {

	jweixin.config({
		debug: false,
		appId: shareSignature.appId,
		timestamp: shareSignature.wxTimestamp,
		nonceStr: shareSignature.wxNoncestr,
		signature: shareSignature.wxSignature,
		openTagList: ['wx-open-launch-weapp'],

		jsApiList: ['checkJsApi',
			'updateAppMessageShareData',
			'updateTimelineShareData',
			'onMenuShareTimeline',
			'onMenuShareAppMessage'
		]
	});
}

function isWeixinBrowser() {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true;
	} else {
		console.info('非微信浏览器');
		return false;
	}
}
